package com.jingdianjichi.wx.handler;


import com.jingdianjichi.wx.redis.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class ReceiveTextMsgHanlder implements WxChatMsgHandler{

    private static final String KEY_WORD = "验证码";

    private static final String LOGIN_PREFIX = "loginCode";

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public WxChatMsgTypeEnum getMsgType() {
        return WxChatMsgTypeEnum.TEXT_MSG;
    }

    @Override
    public String dealMsg(Map<String, String> messageMap) {
        log.info("接收到用户文本消息");
        String content = messageMap.get("Content");
        if(!KEY_WORD.equals(content)){
            return "";
        }

        String fromUserName = messageMap.get("FromUserName");
        String toUserName = messageMap.get("ToUserName");
        Random random = new Random();
        int num = random.nextInt(1000);
        String textContent = "您的验证码是：" + num + "，5分钟内有效";
        String replyContent = "<xml>\n" +
                "  <ToUserName><![CDATA["+fromUserName+"]]></ToUserName>\n" +
                "  <FromUserName><![CDATA["+toUserName+"]]></FromUserName>\n" +
                "  <CreateTime>12345678</CreateTime>\n" +
                "  <MsgType><![CDATA[text]]></MsgType>\n" +
                "  <Content><![CDATA[" + textContent + "]]></Content>\n" +
                "</xml>";

        // 将 登录前缀 和 登录验证码 放进redis，方便其他的微服务进行校验
        // 使用一定的前缀，避免被撞库
        String numKey = redisUtil.buildKey(LOGIN_PREFIX, String.valueOf(num));
        // setex设置具有过期时间的key,value
        // key是验证码，value是用户的openId；通过redis的验证码，后端就能拿到对应的用户openId
        redisUtil.setNx(numKey,fromUserName,5L, TimeUnit.MINUTES);

        return replyContent;
    }

}
